//  metrics data structure

use std::{fmt::Display, sync::Arc};

use anyhow::Result;
use dashmap::DashMap;

// 基本功能 inc/dec/snapshot
#[derive(Debug, Clone)]
pub struct CmpMetrics {
    data: Arc<DashMap<String, i64>>,
}

impl Default for CmpMetrics {
    fn default() -> Self {
        Self::new()
    }
}
impl CmpMetrics {
    pub fn new() -> Self {
        Self {
            data: Arc::new(DashMap::new()),
        }
    }
    pub fn inc(&self, key: impl Into<String>) -> Result<()> {
        let mut count = self.data.entry(key.into()).or_insert(0);
        *count += 1;
        Ok(())
    }
    pub fn dec(&self, key: impl Into<String>) -> Result<()> {
        let mut count = self.data.entry(key.into()).or_insert(0);
        *count -= 1;
        Ok(())
    }
}

impl Display for CmpMetrics {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for ele in self.data.iter() {
            writeln!(f, "{}:{}", ele.key(), ele.value())?;
        }
        Ok(())
    }
}
